<template>
  <div class="findRouteBox">
    <div class="detailWrapBoxCe">
      <div
        style="
          position: relative;
          border-radius: 12px;
          height: 100%;
          min-height: 480px;
          border: 2px solid #003b7a;
        "
      >
        <div class="detailBody">
          <div class="tableScrollBox">
            <el-table
              :data="tableData"
              class="custom-table"
              style="width: 100%"
              :key="currentPage + '-' + tableData.length"
            >
              <el-table-column label="序号" width="80" align="center">
                <template #default="scope">
                  {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
                </template>
              </el-table-column>
              <el-table-column prop="title" label="公告标题" width="420">
                <template #default="scope">
                  <el-tooltip
                    :content="scope.row.title"
                    placement="top-start"
                    custom-class="custom-tooltip"
                    :disabled="!showTooltipMap[`row-${scope.$index}`]"
                    effect="dark"
                  >
                    <span
                      :ref="
                        (el) => el && (titleRefs[`row-${scope.$index}`] = el)
                      "
                      class="title-text"
                    >
                      {{ scope.row.title }}
                    </span>
                  </el-tooltip>
                </template>
              </el-table-column>
              <el-table-column prop="noticeType" label="公告类型" />
              <el-table-column prop="effectiveTime" label="开始时间（UTC）" />
              <el-table-column prop="expireTime" label="结束时间（UTC）" />
              <el-table-column prop="updateTime" label="发布时间（UTC）" />
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button
                    link
                    type="primary"
                    size="small"
                    @click="handleSeeClick(scope.row.id)"
                  >
                    查看
                  </el-button>
                  <el-button
                    v-if="scope.row.attachment"
                    @click="handleDownLoadClick(scope.row.attachment)"
                    link
                    type="primary"
                    size="small"
                    >下载</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-pagination
            class="custom-pagination"
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="pageSize"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
        <div
          class="shawBox"
          style="
            position: absolute;
            z-index: 1;
            top: 0;
            left: 0;
            bottom: 0;
            right: 0;
          "
          v-if="detailBoxRef"
        >
          <div style="float: right; overflow: hidden">
            <el-button type="primary" @click="toBack">返回</el-button>
          </div>
          <p class="shawTitle"><i></i>公告详情：{{ noticeTitle }}</p>
          <div class="contextTextBox" v-html="noticeContent"></div>
          <p class="shawFooter">{{ noticeUpdateTime }}</p>
        </div>
      </div>
    </div>
    <div class="footerTime">
      <p>当前时间(UTC)：{{ utcTime }}</p>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted, watch, nextTick, onUnmounted } from "vue";
import {
  noticesListLimitHomeApi,
  noticesListIdApi,
  noticesDownLoadApi,
} from "@/api/user";
import isValidValue from "@/utils/tools/isValidValue";
import { useTime } from "@/utils/tools/useTime";
import { useEventStore } from "@/store";
const eventStore = useEventStore();
const { utcTime } = useTime();

const titleRefs = ref({});
const showTooltipMap = ref({});

const detailBoxRef = ref(false);
const noticeTitle = ref("");
const noticeContent = ref("");
const noticeUpdateTime = ref("");

const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);
const tableData = ref([]);
// 计算当前页数据
// const currentPageData = computed(() => {
//   const start = (currentPage.value - 1) * pageSize.value;
//   const end = start + pageSize.value;
//   return tableData.value.slice(start, end);
// });

const checkTitleEllipsis = async () => {
  // 等待表格 DOM 完全更新（Element Plus 表格渲染需多轮 nextTick）
  await nextTick();
  await nextTick();

  const refs = titleRefs.value;
  const newMap = {};

  Object.entries(refs).forEach(([key, el]) => {
    if (el) {
      // 强制刷新元素尺寸（避免缓存导致判断不准）
      el.offsetWidth; // 触发重绘
      newMap[key] = el.scrollWidth > el.clientWidth + 1; // +1 容错，避免边界值误判
    }
  });

  showTooltipMap.value = newMap;
};

watch(
  [() => tableData.value, currentPage, pageSize],
  () => {
    // 延迟 100ms（应对表格动画渲染延迟）
    setTimeout(() => {
      checkTitleEllipsis();
    }, 100);
  },
  { deep: true } // 深度监听 tableData 内部变化
);
// 每页条数改变时的回调
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  getNoticesListLimit();
};
// 当前页改变时的回调
const handleCurrentChange = (val) => {
  currentPage.value = val;
  getNoticesListLimit();
};
// 公告-查看
const handleSeeClick = async (id) => {
  eventStore.triggerEvent({ msg: "已查看公告" });
  const { code, data } = await noticesListIdApi(id);
  if (code === 200) {
    detailBoxRef.value = true;
    noticeTitle.value = data.title;
    noticeContent.value = data.content;
    noticeUpdateTime.value = data.updateTime;
    console.log(data);
  }
};
const toBack = () => {
  detailBoxRef.value = false;
};

const handleDownLoadClick = async (attachment) => {
  const { code, data } = await noticesDownLoadApi({
    fileName: attachment,
  });
  if (code === 200) {
    const binaryString = atob(data);
    const len = binaryString.length;
    const uint8Array = new Uint8Array(len);
    for (let i = 0; i < len; i++) {
      uint8Array[i] = binaryString.charCodeAt(i);
    }

    // 创建Blob对象（根据实际文件类型设置MIME类型）
    // 常见类型：text/plain(文本)、application/pdf(PDF)、image/png(图片)等
    const blob = new Blob([uint8Array], { type: "text/plain" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = attachment;
    document.body.appendChild(a);
    a.click();
    // 清理资源，避免内存泄漏
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  }
};
// 获取公告相关
const getNoticesListLimit = async () => {
  const querys = {
    isEffective: "1",
    isPublished: "1",
    pageNum: currentPage.value,
    pageSize: pageSize.value,
  };
  const { code, data } = await noticesListLimitHomeApi(querys);
  if (code === 200) {
    if (isValidValue(data.list)) {
      tableData.value = data.list;
      total.value = data.total;
      checkTitleEllipsis();
    }
  }
};
onMounted(() => {
  getNoticesListLimit();
  window.addEventListener("resize", checkTitleEllipsis);
});
onUnmounted(() => {
  window.removeEventListener("resize", checkTitleEllipsis);
});
</script>
<style lang="scss" scoped>
.findRouteBox {
  height: calc(100vh - 66px);
  min-height: 536px;
  position: relative;
  background-color: #06112a;
  width: 100%;
  min-width: 1280px;
  z-index: 1;
  overflow: hidden;
}
/* // table */
/* 样式保持不变 */
.detailWrapBoxCe {
  padding: 18px 24px 16px 24px;
  width: 100%;
  height: calc(100% - 28px);
  z-index: 1;
  min-width: 1280px;
  box-sizing: border-box;
  .detailBody {
    width: 100%;
    padding: 0 30px;
    padding-top: 15px;
    height: 100%;
    min-height: 470px;
    position: relative;
    overflow: hidden;
  }
  .shawBox {
    // min-height: calc(100vh - 132px);
    overflow: hidden;
    // fill: #fff;
    border-radius: 12px;
    background-color: #081027;
    // filter: drop-shadow(0 0 15px rgba(14, 41, 73, 0.1));
    padding: 25px;
    box-sizing: border-box;
    .shawFooter {
      margin-right: 36px;
      float: right;
      color: #fff;
      font-size: 14px;
      font-weight: 400;
    }
    .contextTextBox {
      color: #fff;
      text-align: left;
      font-size: 14px;
      overflow: hidden;
      padding-left: 36px;
    }
    .shawTitle {
      line-height: 50px;
      clear: both;
      color: #fff;
      text-align: left;
      font-size: 16px;
      font-weight: 700;
      i {
        margin-top: 12px;
        margin-right: 10px;
        float: left;
        width: 24px;
        height: 24px;
        background-image: url("../../assets/images/home/dingwei.png");
        background-position: left center;
        background-size: contain;
        background-repeat: no-repeat;
      }
    }
  }
}
/* 自定义表格样式 */
::v-deep .custom-table .el-table__header {
  height: 40px;
  line-height: 40px;
  background: rgba(0, 175, 255, 0.2);
}
::v-deep .custom-table .el-table__header th {
  font-size: 12px;
  font-weight: 700;
  background: rgba(0, 175, 255, 0.2);
  color: #ffffff;
}
::v-deep .custom-table .el-table__row:nth-child(even) {
  background: rgba(0, 59, 122, 0.2) !important;
}
::v-deep .custom-table .el-table__row:nth-child(odd) {
  background-color: transparent;
}
::v-deep .custom-table .el-table__body td {
  color: #ffffff;
}
/* 自定义分页样式 */
.custom-pagination {
  position: absolute;
  right: 30px;
  bottom: 10px;
}
.custom-pagination .el-pagination__total {
  color: #ffffff;
}
.custom-pagination .el-pagination__sizes {
  color: #ffffff;
}
.custom-pagination .el-pagination__sizes .el-input__inner {
  background-color: transparent;
  color: #ffffff;
  border: 1px solid #3e465e;
}
.custom-pagination .el-pagination__sizes .el-input__inner:hover {
  border-color: #4aadf8;
}
.custom-pagination .el-pagination__btn {
  background-color: transparent;
  color: #ffffff;
  border: 1px solid #3e465e;
}
.custom-pagination .el-pagination__btn:hover {
  background-color: #4aadf8;
  border-color: #4aadf8;
}

.custom-pagination .el-pagination__active {
  background-color: #00a2ff;
  color: #ffffff;
  border: 1px solid #00a2ff;
}
.custom-pagination .el-pagination__jump {
  color: #ffffff;
}
.custom-pagination .el-input__inner {
  background-color: transparent;
  color: #ffffff;
  border: 1px solid #3e465e;
}
.custom-pagination .el-input__inner:hover {
  border-color: #4aadf8;
}
::v-deep .tableScrollBox {
  max-height: calc(100% - 80px);
  min-height: calc(100% - 80px);
  min-height: max(calc(100% - 80px), 420px);
  box-sizing: border-box;
  overflow-y: auto;
}

::v-deep .tableScrollBox::-webkit-scrollbar {
  width: 2px;
}
::v-deep .tableScrollBox::-webkit-scrollbar-track {
  background: rgba(6, 15, 37, 0.5);
  border-radius: 2px;
}

::v-deep .tableScrollBox::-webkit-scrollbar-thumb {
  background: rgba(0, 175, 255, 0.4);
  border-radius: 2px;
}

::v-deep .tableScrollBox::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 175, 255, 0.6);
}

::v-deep .tableScrollBox {
  scrollbar-width: thin;
  scrollbar-color: rgba(0, 175, 255, 0.4) rgba(6, 15, 37, 0.5);
}
/* 表格容器背景透明 */
:deep(.el-table) {
  background-color: transparent !important;
  border: none;
}
:deep(.el-table__body tr) {
  background-color: transparent !important;
}

:deep(.el-table__header tr) {
  color: #c5d6e6;
  font-size: 12px;
  font-weight: 400;
  line-height: 20px;
  background-color: transparent !important;
}
/* 斑马线样式：偶数行 */
:deep(.table-row-even) {
  background-color: rgba(0, 59, 122, 0.2) !important;
}

/* 斑马线样式：奇数行 */
:deep(.table-row-odd) {
  background-color: transparent !important;
}

/* 表格行hover效果 */
:deep(.el-table__row:hover > td) {
  background-color: rgba(0, 59, 122, 0.2) !important;
}

/* 去掉表格默认边框线 */
:deep(.el-table__inner-wrapper::before) {
  background-color: transparent !important;
}
:deep(.el-table__cell) {
  border-bottom: none !important;
}
/* 关键：修改斑马线行的单元格背景色 */
:deep(
    .el-table--striped
      .el-table__body
      tr.el-table__row--striped
      td.el-table__cell
  ) {
  padding: 0;
  background-color: rgba(0, 59, 122, 0.2) !important;
}
:deep(.el-table .cell) {
  padding-right: 0 !important;
}
:deep(.el-pagination__sizes) {
  color: #fff;
}
:deep(.el-pagination__total) {
  color: #fff;
}
:deep(.el-pagination__jump) {
  color: #fff;
}
:deep(.el-pager li) {
  background-color: transparent !important;
  color: #fff;
  border: 1px solid #3e465e;
}
:deep(.el-pager li:hover) {
  background-color: #4aadf8 !important;
  color: #fff;
  border: 1px solid #4aadf8;
}
:deep(.el-pager .is-active) {
  background-color: #4aadf8 !important;
  color: #fff;
  border: 1px solid #4aadf8;
}
:deep(.el-pagination button),
:deep(.el-select__wrapper),
:deep(.el-input__wrapper) {
  background-color: transparent !important;
  color: #fff !important;
  border: 1px solid #003b7a;
}
:deep(.el-pagination .el-input__inner),
:deep(.el-select__placeholder) {
  color: #fff;
}
.footerTime {
  width: 100%;
  height: 28px;
  min-width: 1280px;
  background-color: #050d24;
  p {
    color: #fff;
    text-align: right;
    font-size: 12px;
    line-height: 28px;
    padding-right: 16px;
  }
}
:deep(.el-table .el-table__cell) {
  padding: 4px 0 3px 0;
  font-size: 12px;
}
:deep(.custom-tooltip) {
  background-color: #286bf4 !important;
  color: #fff !important;
  border-radius: 8px !important;
  padding: 8px 12px !important;
  font-size: 12px !important;
}
.title-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: inline-block; // 改为 inline-block，更准确计算宽度
  width: 100%;
  box-sizing: border-box;
  padding: 0 4px; // 预留少量内边距，避免文字贴边
}
</style>
